﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using PmSadis.WebFormsUi.ExpandedControls;
using DevExpress.Web.ASPxGridView;
using DevExpress.Web.Data;
using DevExpress.Web.ASPxGridLookup;
using System.Drawing;
using PmSadis.Repositories.Abstract;
using PmSadis.Models;
using PmSadis.Repositories;

namespace PmSadis.WebFormsUi.Operator
{
    public partial class SubContracts : System.Web.UI.Page
    {
        private const string __operExpandedSubcontractId = "oper-expanded-subcontract-id";
        private IListRepository<SubContract> _repo=new Repositories.SubContractRepository();
        private IListRepository<ObjectInContract> _repoObjects = new Repositories.ObjectInContractRepository();

        protected void gvSubContracts_Init(object sender, EventArgs e)
        {
            var grid=sender as ASPxGridView;
            grid.SetDefaultSettings();
        }

        public IQueryable<PmSadis.Models.SubContract> GetAll()
        {
            return _repo.All.OrderByDescending(x=>x.DateCreate);
        }
        public void InsertSubContract(string name, string blockName)
        {
            var contract = new PmSadis.Models.SubContract {
                ContractId=0,
                Name=name,
                BlockName=blockName
            };
            _repo.Edit(contract);
        }
        public void UpdateSubContract(int contractId, DateTime dateCreate, string name, string blockName)
        {
            var contract = new PmSadis.Models.SubContract
            {
                ContractId = contractId,
                DateCreate=dateCreate,
                Name = name,
                BlockName = blockName
            };
            _repo.Edit(contract);
        }
        public void DeleteSubContract(int contractId)
        {
            _repo.Delete(contractId);
        }

        protected void gvSubContracts_RowUpdating(object sender, ASPxDataUpdatingEventArgs e)
        {
            var grid = sender as ASPxGridView;
            var dateCreate = grid.GetRowValues(grid.EditingRowVisibleIndex, "DateCreate");
            e.NewValues["DateCreate"] = dateCreate;
        }

        public IQueryable<Models.ObjectInContract> SubContractObjects(int subContractId)
        {
            var result = _repoObjects.All.Where(x => x.SubContractId == subContractId);
            return result.OrderBy(x=>x.Object.Code);
        }
        public void UnlinkObject(int objectInContractId)
        {
            (_repoObjects as ObjectInContractRepository).UnlinkObject(objectInContractId);
        }
        public IQueryable GetAllUnlinkedObjects()
        {
            return _repoObjects.All.Where(x => x.SubContractId == null).Select(x => new {
                ObjectInContractId = x.ObjectInContractId,
                Code = x.Object.Code,
                Name = x.Object.Name
            });
        }
        private void LinkObjects(List<int> objectsId, object subContractId, ASPxGridLookup lookup, ASPxGridView grid)
        {
            (_repoObjects as ObjectInContractRepository).LinkObjects(objectsId, Convert.ToInt32(subContractId));

            lookup.DataBind();
            grid.DataBind();
        }

        protected void gvObjects_Init(object sender, EventArgs e)
        {
            var grid=sender as ASPxGridView;
            grid.ForceDataRowType(typeof(Models.ObjectInContract));
        }
        protected void gvObjects_HtmlRowPrepared(object sender, ASPxGridViewTableRowEventArgs e)
        {
            var grid=sender as ASPxGridView;
            if (e.RowType == GridViewRowType.Data)
            {
                var monthBegin = grid.GetRowValuesByKeyValue(e.KeyValue, "MonthBegin");
                var monthEnd = grid.GetRowValuesByKeyValue(e.KeyValue, "MonthEnd");
                if ((monthBegin == null && monthEnd == null) || (Equals(monthBegin, 0) && Equals(monthEnd, 0)))
                {
                    e.Row.CssClass += " empty-month-row";
                }
            }
        }
        protected void gvObjects_BeforePerformDataSelect(object sender, EventArgs e)
        {
            var grid = sender as ASPxGridView;
            var subContractId = grid.GetMasterRowKeyValue();
            Session[__operExpandedSubcontractId] = subContractId;
            grid.SetDefaultSettings();
        }
        protected void btnLinkObjects_Click(object sender, EventArgs e)
        {
            var subContractId = Session[__operExpandedSubcontractId];
            var visibleIndex = gvSubContracts.FindVisibleIndexByKeyValue(subContractId);
            var lookup = gvSubContracts.FindDetailRowTemplateControl(visibleIndex, "lucUnlinkedObjects") as ASPxGridLookup;
            var grid = gvSubContracts.FindDetailRowTemplateControl(visibleIndex, "gvObjects") as ASPxGridView;
            var objectsId = lookup.GridView.GetSelectedFieldValues("ObjectInContractId");
            var list = new List<int>();
            objectsId.ForEach(x =>
            {
                list.Add(Convert.ToInt32(x));
            });
            LinkObjects(list, subContractId, lookup, grid);
        }

        

        public IQueryable<PmSadis.Models.Month> GetMonthes()
        {
            var results = PmSadis.Providers.AppCache.Monthes.OrderBy(x => x.MonthId);
            return results.AsQueryable();
        }

        protected void gvObjects_RowUpdating(object sender, ASPxDataUpdatingEventArgs e)
        {
            var grid = sender as ASPxGridView;
            var monthBegin = Convert.ToInt32(e.NewValues["MonthBegin"]);
            var monthEnd = Convert.ToInt32(e.NewValues["MonthEnd"]);
            if (monthEnd < monthBegin)
            {
                //TODO: встаить валидацию и отображение об ошибке
                e.Cancel=true;
                return;
            }

            var dateCreate = grid.GetRowValues(grid.EditingRowVisibleIndex, "DateCreate");
            var objectId = grid.GetRowValues(grid.EditingRowVisibleIndex, "ObjectId");
            var subContractId = grid.GetRowValues(grid.EditingRowVisibleIndex, "SubContractId");

            dsObjects.UpdateParameters["dateCreate"].DefaultValue = dateCreate.ToString();
            dsObjects.UpdateParameters["monthBegin"].DefaultValue = e.NewValues["MonthBegin"].ToString();
            dsObjects.UpdateParameters["monthEnd"].DefaultValue = e.NewValues["MonthEnd"].ToString();
            dsObjects.UpdateParameters["objectId"].DefaultValue = objectId.ToString();
            dsObjects.UpdateParameters["subContractId"].DefaultValue = subContractId.ToString();
        }
        public void UpdateObjectInContract(int objectInContractId, DateTime dateCreate, int monthBegin, int monthEnd, int objectId, int subContractId)
        {
            var o = new PmSadis.Models.ObjectInContract {
                ObjectInContractId=objectInContractId,
                MonthBegin = monthBegin,
                MonthEnd = monthEnd,
                DateCreate = dateCreate,
                ObjectId = objectId,
                SubContractId=subContractId
            };
            _repoObjects.Edit(o);
        }
    }
}